package com.rmfyzxfw.caseprocess.boot.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rmfyzxfw.caseprocess.boot.annotation.IgnoreResAnnotation;
import com.rmfyzxfw.caseprocess.boot.result.ApiResult;
import com.rmfyzxfw.caseprocess.boot.result.R;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author lixiaoxiang
 * @Description
 * @createTime 2022年06月24日 09:10:00
 */
@RestControllerAdvice(basePackages = {"com.rmfyzxfw.caseprocess.controller"})
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (methodParameter.getMethod().isAnnotationPresent(IgnoreResAnnotation.class)) {
            return o;
        }
        if(Objects.isNull(o)) {
            return R.success();
        }
        if(o instanceof ApiResult) {
            return o;
        }
        if(o instanceof String) {
            return objectMapper.writeValueAsString(R.success(o));
        }
        return R.success(o);
    }
}
